<template>
  <h1>v2</h1>
  <v-btn @click="handleClick">Click me</v-btn>
  <div id="container" class="container"></div>
</template>

<script setup>
const tasks = Array.from({ length: 30 }, (_, i) => () => {
  const div = document.createElement('div');
  div.innerText = i;
  div.className = 'item';
  const container = document.getElementById('container');
  container.appendChild(div);
});

function handleClick() {
  try {
    idlePerformTask(tasks);
  } catch (error) {
    console.error('任务执行失败:', error);
  }
}

function performTask(tasks, scheduler) {
  if (!tasks?.length) return;
  console.log('tasks', tasks);
  let idx = 0;
  function _run() {
    scheduler((goOn) => {
      console.log('goOn', goOn);
      while (goOn() && idx < tasks.length) {
        console.log('tasks', tasks[idx]);
        tasks[idx++]();
      }

      if (idx < tasks.length) {
        _run();
      }
    });
  }
  _run();
}

function idlePerformTask(tasks) {
  const scheduler = (chunkTask) => {
    requestIdleCallback(
      (idle) => {
        chunkTask(() => idle.timeRemaining() > 0);
      }
      // { timeout: 2000 }
    ); // 添加超时保护
  };
  performTask(tasks, scheduler);
}
</script>

<style scoped>
.container {
  margin: 20px auto;
  width: 90%;
  max-width: 1200px;
  height: 600px;
  overflow-y: auto;
  padding: 24px;
  border-radius: 12px;
  background: #ffffff;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  scrollbar-width: thin;
  scrollbar-color: #d4d4d4 #f5f5f5;
}

.item {
  padding: 36px;
  margin: 8px 0;
  background-color: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid #eee;
  color: #333;
  font-size: 14px;
  display: flex;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.item:hover {
  transform: translateX(5px);
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border-color: #e0e0e0;
}
</style>
